package com.gvtv.main.email;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class EmailThread implements Runnable{
	
	private static final Logger logger = Logger.getLogger(EmailThread.class);
	private static EmailThread instance;
	private static byte[] lock = new byte[0];
	private boolean isRunning = true;
	
	private BlockingQueue<EmailInfo> queue;
	private ExecutorService workPool;
	private EmailHandle emailHandle;
	
	public EmailThread(){
		this.queue = new LinkedBlockingQueue<EmailInfo>();
		workPool = Executors.newSingleThreadExecutor();
		emailHandle = new EmailHandle();
	}
	public static EmailThread getInstance(){
		if(instance!=null){
			return instance;
		}else{
			synchronized(lock){
				if(instance!=null){
					return instance;
				}else{
					instance = new EmailThread();
					return instance;
				}
			}
		}
	}
	
	public void addEmailInfo(EmailInfo info){
		try {
			this.queue.put(info);
		} catch (InterruptedException e) {
			logger.error(e);
		}
	}
	
	@Override
	public void run() {
		logger.info("邮件发送线程启动。。。");
		while(!Thread.currentThread().isInterrupted()){
			try {
				EmailInfo emailInfo = this.queue.poll(5, TimeUnit.SECONDS);
				if(emailInfo != null){
					if(StringUtils.isBlank(emailInfo.getEmailCcs())){
						logger.warn("没有指定接收人的邮件地址，无法发送文件。");
						continue;
					}
					while (!emailHandle.sendEmail(emailInfo.getTitle(), emailInfo.toEmailContent(), emailInfo.getEmailTos(), emailInfo.getEmailCcs())) {
						
						Thread.sleep(5 * 1000);
						
					};
				}else {
					if(!isRunning&&queue.size()<=0){
						break;
					}
				}
			} catch (InterruptedException e) {
				logger.error(e);
			}
		}
		logger.info("邮件发送线程结束。。。");
	}

	public void startup() {
		this.workPool.submit(this);
	}

	public void stop() {
		isRunning = false;
		this.workPool.shutdown();
	}
	
	/*public static void main(String[] args) throws InterruptedException{
		getInstance().startup();
		getInstance().addEmailInfo(new EmailInfo());
		Thread.sleep(1000 * 20);
		getInstance().addEmailInfo(new EmailInfo());
		getInstance().stop();
	}*/
}
